import statsmodels.formula.api as smf


def build_ols_table(formulas_by_reg, df, coefs_to_tex_names, path_tex_skeleton,
                    path_tex_output):
    summary_to_tex = dict()
    for i in formulas_by_reg:
        reg = smf.ols(
            formula=formulas_by_reg[i],
            data=df
        ).fit(cov_type='HC0')
        summary_to_tex[f"r_{i}"] = round(reg.rsquared, 2)
        summary_to_tex[f"n_{i}"] = int(reg.nobs)
        for k in coefs_to_tex_names:
            try:
                summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] = str(round(reg.params[k], 3))
                summary_to_tex[f"se_{coefs_to_tex_names[k]}_{i}"] = str(round(reg.HC0_se[k], 3))

                p_value = reg.pvalues[k]
                # Add stars to the coefficients in the table
                if p_value < 0.01:
                    summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] = \
                        summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] + "***"
                if (p_value >= 0.01) & (p_value < 0.05):
                    summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] = \
                        summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] + "**"
                if (p_value >= 0.05) & (p_value < 0.1):
                    summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] = \
                        summary_to_tex[f"{coefs_to_tex_names[k]}_{i}"] + "*"
            except:
                print(f"{k} not in regression {i}")

    # PRODUCE THE TABLE -----------------------------------------------------------------
    with open(path_tex_skeleton, 'r') as f:
        tex = f.read()
        output = tex.format(**summary_to_tex)

    with open(path_tex_output, 'w') as f:
        f.write(output)
